package com.glory.dgcpcpda.activity.mfg;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.activity.check.CheckDescActivity;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.CpcMaterialInfoEntity;
import com.glory.dgcpcpda.entity.CpcToolInfoEntity;
import com.glory.dgcpcpda.entity.SheetInfoEntity;
import com.glory.dgcpcpda.entity.StationDtoEntity;
import com.glory.dgcpcpda.entity.ToolEntity;
import com.glory.dgcpcpda.entity.ToolListEntity;
import com.glory.dgcpcpda.entity.UpdateIPEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ToolUnBindActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etToolID)
    FreeUI_ClearEditText etToolID;
    @BindView(R.id.llToolLayout)
    LinearLayout llToolLayout;
    @BindView(R.id.llLotLayout)
    LinearLayout llLotLayout;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.etEqpWorkPosition)
    FreeUI_ClearEditText etEqpWorkPosition;
    @BindView(R.id.llEqpPositionLayout)
    LinearLayout llEqpPositionLayout;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.llCommentLayout)
    LinearLayout llCommentLayout;
    @BindView(R.id.tvToolID)
    TextView tvToolID;
    @BindView(R.id.ivToolIDArrow)
    ImageView ivToolIDArrow;
    @BindView(R.id.flToolIDList)
    FrameLayout flToolIDList;
    @BindView(R.id.llToolListLayout)
    LinearLayout llToolListLayout;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.tvPosition)
    TextView tvPosition;
    @BindView(R.id.ivPositionArrow)
    ImageView ivPositionArrow;
    @BindView(R.id.flPositionList)
    FrameLayout flPositionList;
    @BindView(R.id.spin_scapCode)
    Spinner spin_scapCode;
    @BindView(R.id.scapCodeLayout)
    LinearLayout scapCodeLayout;
    @BindView(R.id.llMaterial)
    LinearLayout llMaterial;
    @BindView(R.id.llToolQty)
    LinearLayout llToolQty;
    @BindView(R.id.llStationList)
    LinearLayout llStationList;
    @BindView(R.id.etMaterial)
    FreeUI_ClearEditText etMaterial;
    @BindView(R.id.etCdjlefted)
    FreeUI_ClearEditText etCdjlefted;
    private List<String> mToolList;
    private FreeUI_GeneralPop mToolPop;
    private FreeUI_GeneralPop mPositionPop;
    private List<String> mPositionList;
    private List<String> scrapList;
    private ArrayAdapter<String> adapter;
    private String scrapCode;
    private String scrapReason;
    String toolType;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_tool_bind;
    }

    @Override
    protected void initView() {
        tvTitle.setText("Tool解绑设备");
        llCommentLayout.setVisibility(View.GONE);
        llEqpPositionLayout.setVisibility(View.GONE);
        llToolLayout.setVisibility(View.GONE);
        llStationList.setVisibility(View.GONE);
        llToolListLayout.setVisibility(View.VISIBLE);
        //checkbox.setVisibility(View.VISIBLE);
        checkbox.setChecked(true);
        llLotLayout.setVisibility(View.GONE);
        scapCodeLayout.setVisibility(View.VISIBLE);
        llMaterial.setVisibility(View.VISIBLE);
        llToolQty.setVisibility(View.VISIBLE);
        setMainLayout(llMain);
        mToolList = new ArrayList<>();
        mPositionList = new ArrayList<>();
        toolType="";
        String eqpid = getIntent().getExtras().getString("EQPID");
        String toolot=getIntent().getExtras().getString("TOOLID");
        if (eqpid != null){
            etEqpWorkID.setText(eqpid);
            requestTool(eqpid);
        }
        if (toolot!=null){
            tvToolID.setText(toolot);
        }
        if(!tvToolID.getText().toString().equals("")){
            requestMaterialInfo(tvToolID.getText().toString());
        }

        initEdit(etEqpWorkID, s -> requestTool(s));



        tvToolID.addTextChangedListener(new TextWatcher(){

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                System.out.println("beforeTextChanged:"+s);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                System.out.println("onTextChanged:"+s);
                if(checkbox.isChecked()) {

                    requestMaterialInfo(s.toString());


                }
            }

            @Override
            public void afterTextChanged(Editable s) {System.out.println("afterTextChanged:"+s);}

        });
    }

    private void requestTool(String s) {
        FreeUI_EntityCallBack<BaseResponseBean<ToolListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<ToolListEntity>>
                (new TypeToken<BaseResponseBean<ToolListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ToolListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<ToolEntity> toollist = response.body().getResponse().getBody().getTOOLLIST();
                    mToolList.clear();
                    for (ToolEntity entity : toollist){
                        mToolList.add(entity.getTOOLID());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ToolListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"TOOLREPORT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","LOAD");
        map.addProperty("EQUIPMENTID",s);
        NetUtils.requestPostNet("CPC.TOOLREPORT","TOOLREPORT",this,map,callBack);
    }

    private void requestPositionList(String s) {
        FreeUI_EntityCallBack<BaseResponseBean<StationDtoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<StationDtoEntity>>
                (new TypeToken<BaseResponseBean<StationDtoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<StationDtoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    mPositionList.clear();

                    mPositionList.addAll(response.body().getResponse().getBody().getStation());
                    if (mPositionList.size() > 0){
                        tvPosition.setText(mPositionList.get(0));
                        requestEqpInfo(s,mPositionList.get(0));
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<StationDtoEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"GetStationByEqpId");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",s);
        map.addProperty("TOOL_CODE",tvToolID.getText().toString());
        map.addProperty("IS_UP",0);
        map.addProperty("MATERIALTYPE",toolType);
        NetUtils.requestPostNet("GetStationByEqpId","GetStationByEqpId",this,map,callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit,R.id.flToolIDList,R.id.flPositionList,R.id.checkbox})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tvBaseSubmit){
//            if (actionControl("Submit22")) {
//                return;
//            }

            if (getText(etEqpWorkID).equals("") || tvToolID.getText().toString().equals("")) {
                showToast("设备号或ToolID不能为空", false);
                return;
            }
            if(checkbox.isChecked()){

                if("".equals(spin_scapCode.getSelectedItem())){
                    showToast("请选择下机原因！",false);
                    return;
                }else{
                    scrapCode=spin_scapCode.getSelectedItem().toString().split("/")[0];
                    scrapReason=spin_scapCode.getSelectedItem().toString().split("/")[1];
                }
            }else{
                scrapCode="";
                scrapReason="";
            }
            FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要提交?", new FreeUI_CommonCallback() {
                @Override
                public void onSuccess() {
                    FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                            (new TypeToken<BaseResponseBean<JSONObject>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                                showToast("解绑成功",true);
                                finish();
                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<JSONObject>> response) {
                            super.onError(response);
                            loadError(response.getException(),"TOOLREPORT");
                        }
                    };
                    JsonObject map = new JsonObject();
                    map.addProperty("ACTIONTYPE","DOWN");
                    map.addProperty("EQUIPMENTID",getText(etEqpWorkID));
                    map.addProperty("CUTTINGLENGTH",getText(etMaterial));
                    map.addProperty("CDJLEFTED",getText(etCdjlefted));
                    map.addProperty("SITE",tvPosition.getText().toString());
                    List<ToolEntity> toolList = new ArrayList<>();
                    ToolEntity toolEntity = new ToolEntity(tvToolID.getText().toString());
                    String state="";
                    if(!"DL00".equals(scrapCode)&&!"HC00".equals(scrapCode)&&!"DL01".equals(scrapCode)){
                        state="SCRAP";
                    }
                    toolEntity.setSTATE(state);

                    toolEntity.getUDF().put("actionCode",scrapCode);
                    toolEntity.getUDF().put("actionComment","");
                    toolEntity.getUDF().put("actionReason",scrapReason);

                    toolList.add(toolEntity);
                    map.add("TOOLLIST",new JsonParser().parse(new Gson().toJson(toolList)).getAsJsonArray());
                    NetUtils.requestPostNet("CPC.TOOLREPORT","TOOLREPORT",this,map,callBack);
                }
            }, () -> {
            }).show(getSupportFragmentManager(),"TOOLREPORT");
        }else if (view.getId() == R.id.flToolIDList){
            if (mToolList.size() <= 0){
                showToast("未获取到tool列表",false);
                return;
            }else {
                showToolPop();
            }

        }else if(view.getId() == R.id.flPositionList){
                if (tvToolID.getText().toString().equals("")){
                    showToast("请先选择toolID",false);
                    return;
                }
//                if (mPositionList.size() <= 0){
//                    showToast("未获取到站点列表",false);
//                    return;
//                }

                mPositionPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPositionList.getWidth(), mPositionList, ivPositionArrow, (codeS, i) -> {
                    tvPosition.setText(codeS);
                });

                if (mPositionPop.isShowing()) {
                    mPositionPop.dismiss();
                } else {
                    FreeApi_PopUtils.setArrowShow(ivPositionArrow);
                    mPositionPop.showAsDropDown(flPositionList, 0, 0);
                }

        }
       /* else if(view.getId() == R.id.checkbox){
           if(checkbox.isChecked()){
                 if("".equals(tvToolID.getText().toString())){
                    showToast("请先选择要下机的治具批次!",false);
                    checkbox.setChecked(false);
                    return;
                }
               scapCodeLayout.setVisibility(View.VISIBLE);
                requestMaterialInfo(tvToolID.getText().toString());
            }else{
                scapCodeLayout.setVisibility(View.INVISIBLE);
                System.out.println("spin_scapCode:"+ spin_scapCode.getSelectedItem());

            }

        }*/

    }

    private void showToolPop() {
        mToolPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flToolIDList.getWidth(), mToolList, ivToolIDArrow, (codeS, i) -> {
            tvToolID.setText(codeS);
           // requestPositionList(getText(etEqpWorkID));
        });

        if (mToolPop.isShowing()) {
            mToolPop.dismiss();
        } else {
            FreeApi_PopUtils.setArrowShow(ivToolIDArrow);
            mToolPop.showAsDropDown(flToolIDList, 0, 0);
        }
    }

    private void requestMaterialInfo(String mlot){
        FreeUI_EntityCallBack<BaseResponseBean<CpcToolInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<CpcToolInfoEntity>>
                (new TypeToken<BaseResponseBean<CpcToolInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<CpcToolInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    CpcToolInfoEntity.XTool cpcToolInfoEntity = response.body().getResponse().getBody().getXTool();
                    toolType = cpcToolInfoEntity.getEAPPARAM();
                    scrapList=new ArrayList<>();
                    scrapList.add("");
                   if("Suction_Nozzle".equals(toolType)){
                       scrapList.add("DL00/机台待料下机");
                       scrapList.add("HC00/机台换产下机");
                       scrapList.add("XZ01/吸嘴到达寿命");
                       scrapList.add("XZ02/吸嘴磨损");
                       scrapList.add("XZ03/吸嘴破裂");
                       scrapList.add("XZ04/吸嘴脏污");
                       scrapList.add("XZ05/吸嘴丢失");
                       scrapList.add("XZ06/工艺验证");
                   }else if("Thimble".equals(toolType)){
                       scrapList.add("DL00/机台待料下机");
                       scrapList.add("HC00/机台换产下机");
                       scrapList.add("DZ01/顶针到达寿命");
                       scrapList.add("DZ02/顶针断裂");
                       scrapList.add("DZ03/顶针磨损");
                       scrapList.add("DZ04/顶针丢失");
                       scrapList.add("DZ05/工艺验证");
                   }else if("Gaiser".equals(toolType)){
                       scrapList.add("DL00/机台待料下机");
                       scrapList.add("HC00/机台换产下机");
                       scrapList.add("DL01/劈刀清洗下机");
                       scrapList.add("PD01/劈刀到达寿命");
                       scrapList.add("PD02/劈刀堵塞");
                       scrapList.add("PD03/劈刀断裂");
                       scrapList.add("PD04/劈刀用错");
                       scrapList.add("PD05/工艺验证");
                   }else if("Platen".equals(toolType)||"Guide".equals(toolType)||"DAG".equals(toolType)){
                       scrapList.add("DL00/清洗下机");
                       scrapList.add("HC00/换产下机");
                   }else if("Gold_Finger".equals(toolType)||"SOCKET".equals(toolType)||"TestSamples".equals(toolType)||"DUT".equals(toolType)||"Conversion_piece".equals(toolType)){
                       scrapList.add("DL00/机台待料下机");
                   }
                   else{
                       scrapList.add("DL00/机台待料下机");
                       scrapList.add("DJ00/治具用完");

                   }
                    adapter= new ArrayAdapter<String>(ToolUnBindActivity.this,android.R.layout.simple_spinner_item,scrapList);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spin_scapCode.setAdapter(adapter);
                    requestPositionList(getText(etEqpWorkID));
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<CpcToolInfoEntity>> response) {
                super.onError(response);
                System.out.println("456123");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("MLOTID",mlot);
        map.addProperty("ACTIONTYPE","QUERYBYID");
        map.addProperty("EQUIPMENTID",getText(etEqpWorkID));
        NetUtils.requestPostNet("CPC.FINDMLOTBYID", "TRANSFERMES",this, map, callBack);
    }

    private void requestEqpInfo(String eqp,String Position){
        FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
                (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    UpdateIPEntity body = response.body().getResponse().getBody();
                    //body.getEQPTYPE().equals("DISCO_DFD6361")||
                    if(body.getEQPTYPE().equals("DISCO_DFD6362")){
                        List<CheckDescActivity.EAPCheckEntity.CheckEntity> checkList = new ArrayList<>();
                        if(Position.equals("站点一")){
                            CheckDescActivity.EAPCheckEntity.CheckEntity checkEntity = new CheckDescActivity.EAPCheckEntity.CheckEntity("BLADE_L1");
                            checkList.add(checkEntity);
                            CheckDescActivity.EAPCheckEntity.CheckEntity checkEntity1 = new CheckDescActivity.EAPCheckEntity.CheckEntity("BLADE_EDGE");
                            checkList.add(checkEntity1);
                        }
                        if(Position.equals("站点二")){
                            CheckDescActivity.EAPCheckEntity.CheckEntity checkEntity = new CheckDescActivity.EAPCheckEntity.CheckEntity("BLADE_L2");
                            checkList.add(checkEntity);
                            CheckDescActivity.EAPCheckEntity.CheckEntity checkEntity1 = new CheckDescActivity.EAPCheckEntity.CheckEntity("BLADE_EDGE2");
                            checkList.add(checkEntity1);
                        }
                        requestEqpCurrentParamter(eqp,checkList);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "GETEQPINFOBYEQPID");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("EQPID",eqp);
        NetUtils.requestPostNet("EAP.GETEQPINFOBYEQPID","GETEQPINFOBYEQPID",this,map,callBack);
    }

    private void requestEqpCurrentParamter(String eqp,List<CheckDescActivity.EAPCheckEntity.CheckEntity> checkList){
        FreeUI_EntityCallBack<BaseResponseBean<CheckDescActivity.EAPCheckEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<CheckDescActivity.EAPCheckEntity>>
                (new TypeToken<BaseResponseBean<CheckDescActivity.EAPCheckEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<CheckDescActivity.EAPCheckEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    List<CheckDescActivity.EAPCheckEntity.CheckEntity> paramterlist = response.body().getResponse().getBody().getPARAMTERLIST();
                    if (paramterlist.size() <= 0) {
                        showToast("EAP返回参数信息为空，请手动输入参数!",false);
                        return;
                    }
                    for (CheckDescActivity.EAPCheckEntity.CheckEntity checkEntity : paramterlist) {
                        if(checkEntity.getValue().equals(null)||checkEntity.getValue().equals(""))
                        {
                            showToast("EAP返回参数信息为空，请手动输入参数!",false);
                            return;
                        }
                        if(checkEntity.getName().contains("BLADE_L")){
                            Double blade = Double.parseDouble(checkEntity.getValue())/1000;
                            etMaterial.setText(String.valueOf(blade));
                        }
                        if(checkEntity.getName().contains("BLADE_EDGE")){
                            Double blade = Double.parseDouble(checkEntity.getValue())/1000;
                            etCdjlefted.setText(String.valueOf(blade));
                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<CheckDescActivity.EAPCheckEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "CHECKSHEET");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQPID", eqp);
        map.add("PARAMTERLIST", new JsonParser().parse(new Gson().toJson(checkList)).getAsJsonArray());
        NetUtils.requestPostNet("CPC.GetEqpCurrentParamter", "GetEqpCurrentParamter", this, map, callBack);
    }
}
